package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Cart;
import mydessertstore.domain.CartItem;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Iterator;

public class UpdateCartByInputServlet extends HttpServlet{
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");
        //从对话中，获取购物车
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while(cartItems.hasNext()){
            CartItem cartItem =(CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try{
                String str = req.getParameter("itemId");
                String []array=str.split(",");
                String []array_2=array[1].split("=");
                if(itemId.equals(array[0]))
                    cart.setQuantityByItemId(itemId, Integer.parseInt(array_2[1]));
                //取到值以后如果无数量就不显示了
                if(Integer.parseInt(array[1])<1)
                {
                    cartItems.remove();
                }
            }catch(Exception e){
            }
        }
        session.setAttribute("cart", cart);

        Cart cart2 = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator2 = cart2.getAllCartItems();
        String quantityAll = "";
        while (cartItemIterator2.hasNext()) {
            //产品数量增加
            CartItem cartItem2 = cartItemIterator2.next();
            int quantity2 = cartItem2.getQuantity();
            quantityAll += quantity2 + "," + cartItem2.getTotal() + "," + cart2.getSubTotal();
        }
        resp.setContentType("text/xml");
        PrintWriter out = resp.getWriter();
        out.write(quantityAll);


        req.getRequestDispatcher(CART_FORM).forward(req,resp);
        resp.setHeader("Access-Control-Allow_Origin","*");
    }
}